// edit.js 逻辑文件
Page({
  data: {
    noteId: null,
    noteTitle: '',
    noteContent: '',
    importance: 'medium', // 默认重要性
  },

  onLoad(options) {
    // 如果是编辑模式，获取传入的便签ID
    if (options.id) {
      this.setData({ noteId: options.id });
      this.loadNoteData(options.id);
    }
  },

  // 加载便签数据（实际项目中应请求API）
  loadNoteData(id) {
    const notes = wx.getStorageSync('notes') || [];
    const note = notes.find(item => item.id === id);
    if (note) {
      this.setData({
        noteTitle: note.title,
        noteContent: note.content,
        importance: note.importance || 'medium'
      });
    }
  },

  // 输入处理
  onTitleInput(e) {
    this.setData({ noteTitle: e.detail.value });
  },

  onContentInput(e) {
    this.setData({ noteContent: e.detail.value });
  },

  // 设置重要性
  setImportance(e) {
    this.setData({ importance: e.currentTarget.dataset.level });
  },

  // 保存便签
  onSave() {
    const { noteId, noteTitle, noteContent, importance } = this.data;
    
    if (!noteTitle.trim()) {
      wx.showToast({
        title: '标题不能为空',
        icon: 'none'
      });
      return;
    }

    // 构造便签对象
    const newNote = {
      id: noteId || Date.now(), // 新便签使用时间戳作为ID
      title: noteTitle,
      content: noteContent,
      importance,
      time: new Date().toLocaleString(),
      star: false
    };

    // 保存到本地存储（实际项目应请求API）
    const notes = wx.getStorageSync('notes') || [];
    if (noteId) {
      // 更新现有便签
      const index = notes.findIndex(n => n.id === noteId);
      if (index !== -1) notes[index] = newNote;
    } else {
      // 添加新便签
      notes.unshift(newNote);
    }
    
    wx.setStorageSync('notes', notes);
    
    wx.showToast({
      title: '保存成功',
      icon: 'success',
      duration: 1500,
      complete: () => {
        setTimeout(() => {
          wx.navigateBack();
        }, 1500);
      }
    });
  },

  // 取消编辑
  onCancel() {
    wx.navigateBack();
  }
});